package top.fzqblog.firstapp;

import android.annotation.SuppressLint;
import android.app.ActivityOptions;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.PaintDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.provider.Settings;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.NotificationCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jakewharton.rxbinding.view.RxView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import retrofit2.converter.simplexml.SimpleXmlConverterFactory;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import top.fzqblog.broadcast.MyBroadCast;
import top.fzqblog.event.MsgEvent;
import top.fzqblog.http.api.MusicListApi;
import top.fzqblog.http.api.RetrofitApi;
import top.fzqblog.http.api.SongApi;
import top.fzqblog.model.Meizi;
import top.fzqblog.model.MusicList;
import top.fzqblog.model.Results;
import top.fzqblog.model.Song;
import top.fzqblog.music.activity.MusicMain;
import top.fzqblog.service.ApiFactory;
import top.fzqblog.service.RequestService;
import top.fzqblog.service.SongService;
import top.fzqblog.sysservice.BindService;
import top.fzqblog.sysservice.BindServiceConnection;
import top.fzqblog.sysservice.StartService;
import top.fzqblog.util.ApiConstant;
import top.fzqblog.util.XmlUtil;
import top.fzqblog.utils.Constants;
import top.wefor.circularanim.CircularAnim;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.btn_flatBtn)
     Button btn_flatBtn;
    
    @OnClick(R.id.btn_flatBtn)
    public void flatBtnClick(){
        Toast.makeText(this, "flatBtn点击了一下", Toast.LENGTH_SHORT).show();
    }

    @OnClick(R.id.btn_imageViewPager)
    public void imageViewPagerTest(){
        startActivity(new Intent(this, ImageViewPagerTest.class));
    }

    @OnClick(R.id.btn_cardView)
    public void cardViewClick(){
        startActivity(new Intent(this, CardViewTest.class));
    }

    @OnClick(R.id.btn_tabLayout)
    public void tabLayoutClick(){
        startActivity(new Intent(this, TabLayoutTest.class));
    }

    @OnClick(R.id.btn_toolbar)
    public void toolBarClick(){
        startActivity(new Intent(this, ToolbarTest.class));
    }

    @OnClick(R.id.btn_collapsingToolbarLayout)
    public void collapsingToolbarLayoutClick(){
        startActivity(new Intent(this, CollapsingToolbarLayoutTest.class));
    }

    @OnClick(R.id.btn_drawerLayout)
    public void drawerlayoutClick(){
        startActivity(new Intent(this, DrawerLayoutTest.class));
    }

    @OnClick(R.id.btn_retrofitTest)
    public void retrofitTestClick(){
        Retrofit retrofit = new Retrofit
                .Builder()
                .baseUrl("http://gank.io/api/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        RetrofitApi retrofitApi = retrofit.create(RetrofitApi.class);
        Call<Meizi> call = retrofitApi.getMeizi("福利", 20, 1);
        call.enqueue(new Callback<Meizi>() {
            @Override
            public void onResponse(Call<Meizi> call, Response<Meizi> response) {
                Meizi meizi = response.body();
//              Toast.makeText(MainActivity.this, "Meizi：" + meizi, Toast.LENGTH_SHORT).show();
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder
                        .setTitle("请求内容")
                        .setMessage(meizi.toString())
                        .show();
            }

            @Override
            public void onFailure(Call<Meizi> call, Throwable throwable) {
//             Toast.makeText(MainActivity.this, "错误："+ throwable, Toast.LENGTH_SHORT).show()
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder
                        .setTitle("错误内容")
                        .setMessage(throwable.toString())
                        .show();
            }
        });
    }

    @OnClick(R.id.btn_retrofitAndGlide)
    public void ReftrofitGlideClick(){
        startActivity(new Intent(this, RetrofitGlideTest.class));
    }

    @OnClick(R.id.btn_rxjavaRetrofitAndGlide)
    public void RxjavaRetrofitAndGlide(){
        startActivity(new Intent(this, RxjavaRetrofitGlide.class));
    }

    @OnClick(R.id.btn_rxjavaTest)
    public void RxJavaClick(){
        Log.i("tag", "rxjava测试");
        Observable
                .from(new String[]{"1", "2", "3"})
                .doOnNext(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show();
                    }
                })
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String name) {
                        Log.i("tag", name);
                    }
                });
    }

    @OnClick(R.id.btn_xrecyclerView)
    public void XRecyclerViewClick(){
        startActivity(new Intent(this, XRecyclerViewTest.class));
    }

    @OnClick(R.id.btn_smartRefreshLayoutTest)
    public void smartRefreshLayoutClick(){
        startActivity(new Intent(this, SmartRefreshLayoutTest.class));
    }

    @BindView(R.id.btn_getPicture)
    public Button btn_getPic;

    @BindView(R.id.btn_photoSee)
    public Button photoSee;

    @BindView(R.id.btn_rippleTest)
    public Button btnRipple;

    @BindView(R.id.btn_floating)
    public Button btnFloating;

    @BindView(R.id.btn_topLayout)
    public Button btnTopLayout;

    @BindView(R.id.btn_music)
    public Button btnMedia;

    @BindView(R.id.btn_video)
     public Button btnVideo;

    @BindView(R.id.btn_eventBus)
    public Button btnEventBus;

    @BindView(R.id.broadCast)
    public Button broadCast;

    @BindView(R.id.btn_service)
    public Button btnService;

    @BindView(R.id.btn_BindService)
    public Button btnBindService;

            
    RequestService requestService = new RequestService();

    BindServiceConnection bindServiceConnection;

    private void initRxBinding(){
        RxView
                .clicks(btn_getPic)
                .throttleFirst(1, TimeUnit.SECONDS)//一秒内的多次点击只取响应第一次
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        startActivity(new Intent(MainActivity.this, GetPicTest.class));
                    }
                });

        RxView
                .clicks(photoSee)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(
                        aVoid -> {
                                requestService.getMeizi(new Subscriber<Meizi>() {
                                    @Override
                                    public void onCompleted() {

                                    }

                                    @Override
                                    public void onError(Throwable throwable) {

                                    }

                                    @Override
                                    public void onNext(Meizi meizi) {
                                        ArrayList<String> list = new ArrayList<>();
                                        for (Results results : meizi.getResults()) {
                                            list.add(results.getUrl());
                                        }
                                        Intent intent = new Intent(MainActivity.this, PhotoSee.class);
                                        intent.putStringArrayListExtra("imgs", list);
                                        intent.putExtra("position", 3);
                                        startActivity(intent);
                                    }
                                }, "福利", 20, 1);

//                            Intent intent = new Intent(MainActivity.this, PhotoSee.class);
//                            intent.putStringArrayListExtra("imgs", new ArrayList<String>(){{
//                                add("https://ws1.sinaimg.cn/large/610dc034ly1fk05lf9f4cj20u011h423.jpg");
//                                add("https://ws1.sinaimg.cn/large/610dc034ly1fjs25xfq48j20u00mhtb6.jpg");
//                                add("https://ws1.sinaimg.cn/large/610dc034ly1fjqw4n86lhj20u00u01kx.jpg");
//                            }});
//                            startActivity(intent);

                        }
                );

        RxView
                .clicks(btnRipple)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(
                        Void ->{

//                            songService.getSong(
//                                    new Subscriber<Song>() {
//                                        @Override
//                                        public void onCompleted() {
//
//                                        }
//
//                                        @Override
//                                        public void onError(Throwable throwable) {
//                                            Log.i(Constants.TAG, "onError: " + throwable);
//                                        }
//
//                                        @Override
//                                        public void onNext(Song song) {
//                                            Toast.makeText(MainActivity.this, "song" + song.toString(), Toast.LENGTH_SHORT).show();
//                                        }
//                                    }
//                                    ,"MUSIC_27103210"
//                            );
                        }
                );

        RxView
                .clicks(btnFloating)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(
                        Void ->{
                            startActivity(new Intent(MainActivity.this, FloatingBtnTest.class));
                        }
                );

        RxView
                .clicks(btnTopLayout)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(
                        Void ->{
                            startActivity(new Intent(MainActivity.this, TopLaoutTest.class));
                        }
                );

        RxView
                .clicks(btnMedia)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(
                        Void -> {
                                startActivity(new Intent(MainActivity.this, MusicTest.class));
                        }
                );

        RxView
                .clicks(btnVideo)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(
                        Void ->{
                            startActivity(new Intent(MainActivity.this, VideoTest.class));
                        }
                );

        RxView
                .clicks(btnEventBus)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(
                        Void ->{
                            startActivity(new Intent(MainActivity.this, EventBusTest.class));
                        }
                );

        RxView
                .clicks(broadCast)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(
                        Void -> {
                            Toast.makeText(this, "发送广播", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(MainActivity.this, MyBroadCast.class);
                            //intent.setAction("top.fzqblog.firstapp.broastTest"); //5.0后不能使用setAction了
                            intent.putExtra("msg", "消息");
                            sendBroadcast(intent);
                        }
                );

        RxView
                .clicks(btnService)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(
                        Void -> {
                            Intent intent = new Intent(MainActivity.this, StartService.class);
                            intent.putExtra("msg", "startService");
                            startService(intent);
                        }
                );

        RxView
                .clicks(btnBindService)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(
                        Void -> {
                            Intent intent = new Intent(MainActivity.this, BindService.class);
                            intent.putExtra("msg", "bindService");
                            bindService(intent, this.bindServiceConnection, Context.BIND_AUTO_CREATE);
                        }
                );

        RxView
                .clicks(btnTransition)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(
                        Void -> {
                            CircularAnim.fullActivity(MainActivity.this, btnTransition)
                                    .colorOrImageRes(R.color.colorPrimary)
                                    .go(() -> {
                                        ActivityOptionsCompat options =
                                            ActivityOptionsCompat.makeSceneTransitionAnimation(MainActivity.this,
                                                    btnTransition, "a");//与xml文件对应
                                    startActivity(new Intent(MainActivity.this, TransitionTest.class), options.toBundle());
                                    });
//                            ActivityOptionsCompat options =
//                                    ActivityOptionsCompat.makeSceneTransitionAnimation(this,
//                                            btnTransition, "a");//与xml文件对应
//                            startActivity(new Intent(MainActivity.this, TransitionTest.class), options.toBundle());
                        }
                );

        RxView
                .clicks(btnPlayer)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(
                        Void -> {
                            startActivity(new Intent(this, MusicMain.class));
                        }
                );

        RxView
                .clicks(btnRetrofit)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(
                        Void -> {
                            SongService songService = new SongService();
                            songService.getMusicList(new Subscriber<MusicList>() {
                                @Override
                                public void onCompleted() {

                                }

                                @Override
                                public void onError(Throwable throwable) {

                                }

                                @Override
                                public void onNext(MusicList musicList) {
                                    Toast.makeText(MainActivity.this, "music" + musicList, Toast.LENGTH_SHORT).show();
                                }
                            },"谁来剪月光");
                        }
                );

        RxView
                .clicks(retrofitToXml)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(
                        Void -> {
                            SongService songService = new SongService();
                            songService.getSong(new Subscriber<Song>() {
                                @Override
                                public void onCompleted() {
                                }
                                @Override
                                public void onError(Throwable throwable) {
                                }
                                @Override
                                public void onNext(Song song) {
                                    Toast.makeText(MainActivity.this, "song" + song, Toast.LENGTH_SHORT).show();
                                }
                            },"MUSIC_27103210");
                        }
                );

        RxView
                .clicks(btnScrollView)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(
                        Void -> {
                            startActivity(new Intent(MainActivity.this, MyScrollViewTest.class));
                        }
                );

        RxView
                .clicks(btnObservableScrollView)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(
                        Void -> {
                            startActivity(new Intent(MainActivity.this, ObservableViewTest.class));
                        }
                );
    }

    @BindView(R.id.btn_transition)
    public Button btnTransition;

    @BindView(R.id.btn_player)
    public Button btnPlayer;

    @BindView(R.id.btn_retrofit)
    public Button btnRetrofit;

    @BindView(R.id.retrofitToXml)
    public Button retrofitToXml;

    @BindView(R.id.btn_scrollView)
    public Button btnScrollView;

    @BindView(R.id.observableScrollView)
    public Button btnObservableScrollView;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MsgEvent msgEvent){
        Toast.makeText(this, msgEvent.getMsg(), Toast.LENGTH_SHORT).show();
    }


//    @BindView(R.id.btn_popUpWindow)
//    Button btn_popUpWindow;

    private PopupWindow popupWindow;

    @OnClick(R.id.btn_popUpWindow)
    public void popUpBtnClick(){
        View popUpLayout = LayoutInflater.from(this).inflate(R.layout.pop_up_layout, null);
        popupWindow = new PopupWindow(popUpLayout, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);//true锁定界面
        //popUpLayout.setFocusable(true);
        popupWindow.setBackgroundDrawable(new PaintDrawable());
        View rootview = LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_main, null);

        WindowManager.LayoutParams lp = getWindow().getAttributes();//设置背景透明
        lp.alpha = 0.5F; //0.0-1.0
        getWindow().setAttributes(lp);

        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {//监听popupWindow消失
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1F; //0.0-1.0
                getWindow().setAttributes(lp);
            }
        });

//        popupWindow.setAnimationStyle(R.style.popUpAnimation);
        popupWindow.showAtLocation(rootview, Gravity.BOTTOM, 0, 0);
    }



    public void popUpClick(View view){
        switch (view.getId()){
            case R.id.choose1:
                popupWindow.dismiss();
                Toast.makeText(this, "点击了1", Toast.LENGTH_SHORT).show();
                break;
            case R.id.choose2:
                popupWindow.dismiss();
                Toast.makeText(this, "点击了2", Toast.LENGTH_SHORT).show();
                break;
            case R.id.choose3:
                popupWindow.dismiss();
                Toast.makeText(this, "点击了3", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);//ButterKnife绑定view

        EventBus.getDefault().register(this);//注册eventbus

        bindServiceConnection = new BindServiceConnection();

        initRxBinding();

        Log.i("tag", "-----onCreate");

        Button btn = (Button) findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                startActivity(intent);
            }
        });

        Button btnSATest = (Button) findViewById(R.id.sa_btn);//simpleAdapterTest
        btnSATest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, SimpleAdapterTestActivity.class);
                startActivity(intent);
            }
        });

        Button btnCustomAdapter = (Button) findViewById(R.id.custom_btn);//自定义adapter
        btnCustomAdapter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, CustomAdapterTest.class);
                startActivity(intent);
            }
        });

        Button btnNormalJump = (Button) findViewById(R.id.btn_normalJump);//常用跳转
        btnNormalJump.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setAction("top.fzqblog.firstapp.DialActivity.action");//隐式跳转
                startActivity(intent);
            }
        });

        Button btnNetPerm = (Button) findViewById(R.id.btn_netPerm);
        btnNetPerm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ConnectivityManager connectivityManager = (ConnectivityManager) MainActivity.this.getSystemService(CONNECTIVITY_SERVICE);
                NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
                if(networkInfo !=null && networkInfo.isAvailable()){
                    Toast.makeText(MainActivity.this, "网络可用", Toast.LENGTH_SHORT).show();
                }
                else{
                    Toast.makeText(MainActivity.this, "网络不可用", Toast.LENGTH_SHORT).show();
                }
                NetworkInfo.State state = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
                if(state == NetworkInfo.State.CONNECTED){
                    Toast.makeText(MainActivity.this, "数据网络已连接", Toast.LENGTH_SHORT).show();
                }
                state = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
                if(state == NetworkInfo.State.CONNECTED){
                    Toast.makeText(MainActivity.this, "wifi已连接", Toast.LENGTH_SHORT).show();
                }

                if(state == NetworkInfo.State.DISCONNECTED){
                    startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
                }
            }
        });

        Button btn_search = (Button) findViewById(R.id.btn_search);
        btn_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MainActivity.this, WebViewTest.class));
            }
        });

        Button btn_timePick = (Button) findViewById(R.id.btn_timePick);
        btn_timePick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MainActivity.this, DateTimePickTest.class));
            }
        });

        Button btn_progress = (Button) findViewById(R.id.btn_progress);
        btn_progress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, ProgressBarTest.class));
            }
        });

        Button btn_fragment = (Button) findViewById(R.id.btn_fragment);
        btn_fragment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, FragmentTest.class));
            }
        });

        Button btn_dynamicFragment = (Button) findViewById(R.id.btn_dynamicFragment);
        btn_dynamicFragment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MainActivity.this, DynamicFragmentTest.class));
            }
        });

        Button btn_viewpagetest = (Button) findViewById(R.id.btn_viewpagetest);
        btn_viewpagetest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, ViewPageTest.class));
            }
        });

        Button btn_viewFlipperTest= (Button) findViewById(R.id.btn_viewFlipperTest);
        btn_viewFlipperTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, ViewFlipperTest.class));
            }
        });

        Button btn_alterDialog = (Button) findViewById(R.id.btn_alterdialog);
        btn_alterDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder
                        .setTitle("对话框")
                         .setMessage("啦啦啦啦")
                        .show();
            }
        });

        Button btn_notifacation = (Button) findViewById(R.id.btn_notifacation);
        final NotificationManager mNotifyMgr =
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        btn_notifacation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent mainIntent = new Intent(MainActivity.this, MainActivity.class);
                PendingIntent mainPendingIntent = PendingIntent.getActivity(MainActivity.this, 0, mainIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
                builder
                        .setContentTitle("通知标题")
                        .setContentText("通知内容")
                        .setWhen(System.currentTimeMillis())
                        .setSmallIcon(R.mipmap.ic_launcher_round)
                        .setDefaults(Notification.DEFAULT_ALL)
                        .setAutoCancel(true)
                        .setContentIntent(mainPendingIntent);
                mNotifyMgr.notify(1,builder.build());
            }
        });

        Button btn_progressbarTest = (Button) findViewById(R.id.btn_progressDialogTest);
        btn_progressbarTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
                progressDialog.setTitle("下载中");
                progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                progressDialog.setIndeterminate(false);
                progressDialog.show();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        int i = 0;
                        while ( i < 100) {
                            progressDialog.incrementProgressBy(1);
                            try {
                                Thread.sleep(200);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            i ++;
                        }
                        progressDialog.dismiss();
                    }
                }).start();
            }
        });

        Button btn_RecycleViewTest = (Button) findViewById(R.id.btn_recycleViewTest);
        btn_RecycleViewTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MainActivity.this, RecycleViewTest.class));
            }
        });

        Button btn_NoHandlerTest = (Button) findViewById(R.id.btn_NoHandlerTest);
        btn_NoHandlerTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
                progressDialog.setCancelable(false);
                progressDialog.setTitle("请求中");
                progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                progressDialog.show();

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            URL url = new URL("https://way.jd.com/jisuapi/get?channel=头条&num=40&start=0&appkey=2334c5bbef68220f34698861ee1c0fb3");
                            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                            InputStream inputStream = httpURLConnection.getInputStream();
                            progressDialog.setMax(httpURLConnection.getContentLength());
                            final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                            byte[] bytes = new byte[1024];
                            int len = -1;
                            while (-1 != (len = inputStream.read(bytes))) {
                                progressDialog.incrementProgressBy(len);
                                byteArrayOutputStream.write(bytes, 0, len);
                                byteArrayOutputStream.flush();
                                SystemClock.sleep(50);
                            }
                            System.out.println("获得内容：" + byteArrayOutputStream.toString());
                            inputStream.close();
                            byteArrayOutputStream.close();
                            httpURLConnection.disconnect();
                            progressDialog.dismiss();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                                    builder
                                            .setTitle("请求内容")
                                            .setMessage(byteArrayOutputStream.toString())
                                            .show();
                                }
                            });
                        }catch (IOException e){
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });

        Button btn_withHandlerTest = (Button) findViewById(R.id.btn_withHandlerTest);
        btn_withHandlerTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
                progressDialog.setCancelable(false);
                progressDialog.setTitle("请求中");
                progressDialog.setIndeterminate(false);
                progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                progressDialog.show();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            URL url = new URL("https://way.jd.com/jisuapi/get?channel=头条&num=40&start=0&appkey=2334c5bbef68220f34698861ee1c0fb3");
                            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                            progressDialog.setMax(httpURLConnection.getContentLength());
                            InputStream inputStream = httpURLConnection.getInputStream();
                            final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                            byte[] bytes = new byte[1024];
                            int len = -1;
                            while (-1 != (len = inputStream.read(bytes))) {
                                progressDialog.incrementProgressBy(len);
                                byteArrayOutputStream.write(bytes, 0, len);
                                byteArrayOutputStream.flush();
                                SystemClock.sleep(50);
                            }
                            System.out.println("获得内容：" + byteArrayOutputStream.toString());
                            Message message = Message.obtain();
                            message.what = 1;
                            message.obj = byteArrayOutputStream.toString();
                            handler.sendMessage(message);//使用handler发送消息
                            inputStream.close();
                            byteArrayOutputStream.close();
                            progressDialog.dismiss();
                        }catch (IOException e){
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });


        final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        Button btn_AsyncTaskTest = (Button) findViewById(R.id.btn_asyncTaskTest);
        btn_AsyncTaskTest.setOnClickListener(new View.OnClickListener() {

            @SuppressLint("StaticFieldLeak")
            @Override
            public void onClick(View view) {
                new AsyncTask<String, Integer, String>() {

                    @Override
                    protected void onPreExecute() {
                        progressDialog.show();
                    }

                    @Override
                    protected String doInBackground(String... strings) {
                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                        try {
                            URL url = new URL("https://way.jd.com/jisuapi/get?channel=头条&num=40&start=0&appkey=2334c5bbef68220f34698861ee1c0fb3");
                            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                            progressDialog.setMax(httpURLConnection.getContentLength());
                            InputStream inputStream = httpURLConnection.getInputStream();
                            byte[] bytes = new byte[1024];
                            int len = -1;
                            while (-1 != (len = inputStream.read(bytes))) {
                                publishProgress(len);
                                byteArrayOutputStream.write(bytes, 0, len);
                                byteArrayOutputStream.flush();
                                SystemClock.sleep(50);
                            }
                            System.out.println("获得内容：" + byteArrayOutputStream.toString());
                            inputStream.close();
                            byteArrayOutputStream.close();
                        }catch (IOException e){
                            e.printStackTrace();
                        }
                        return byteArrayOutputStream.toString();
                    }


                    @Override
                    protected void onPostExecute(String result) {
                        progressDialog.dismiss();
                        AlertDialog.Builder builder= new AlertDialog.Builder(MainActivity.this);
                        builder.setTitle("请求结果：")
                                    .setCancelable(false)
                                    .setMessage(result)
                                    .show();
                    }

                    @Override
                    protected void onProgressUpdate(Integer... values) {
                        progressDialog.incrementProgressBy(values[0]);
                    }
                }.execute();
            }
        });


        Button btn_animationTest = (Button) findViewById(R.id.btn_animationTest);
        btn_animationTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MainActivity.this, AnimationTest.class));
            }
        });

        Button btn_FileTest = (Button) findViewById(R.id.btn_FileTest);
        btn_FileTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MainActivity.this, FileTestActivity.class));
            }
        });


    }

    /**
     * handler 处理消息
     */
    @SuppressLint("HandlerLeak")
    private  Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder
                    .setTitle("请求内容")
                    .setMessage(msg.obj.toString())
                    .show();
        }
    };



    @Override
    protected void onStart() {
        super.onStart();
        Log.i("tag", "-----onStart");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i("tag", "-----onRestart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i("tag", "-----onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i("tag", "-----onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i("tag", "-----onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i("tag", "-----onDestroy");
        EventBus.getDefault().unregister(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        //填充选项菜单（读取XML文件、解析、加载到Menu组件上）
        // getMenuInflater().inflate(R.menu.main, menu);

        //通过代码的方式来添加Menu
        //添加菜单项（组ID，菜单项ID，排序，标题）
        menu.add(0, 1, 100, "Start");
        menu.add(0, 2, 200, "Over");
        //添加子菜单
        SubMenu sub1 = menu.addSubMenu("setting");
        sub1.add(1, 3, 0, "声音设置");
        sub1.add(1, 4, 400, "背景设置");
        return true;
    }

    Handler exitHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            exit = false;
        }
    };


    private boolean exit = false;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            if(exit){
               finish();
               System.exit(0);
            }else{
                exitHandler.sendEmptyMessageDelayed(1, 2000);
                Toast.makeText(this, "再按一次就退出了哦！", Toast.LENGTH_SHORT).show();
                exit = true;
                return false;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
